<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style></style>
  </head>
  <body>
    <div>Either函子</div>
    <p>Either两者中底任何一个,类是于if---else的处理</p>
    <p>异常会让函数变得不纯,Either函子可以用来处理异常</p>
    <script>
      class Left {
        static of(value) {
          return new Left(value);
        }
        constructor(value) {
          this._value = value;
        }
        map(fn) {
          return this;
        }
      }

      class Right {
        static of(value) {
          return new Right(value);
        }
        constructor(value) {
          this._value = value;
        }
        map(fn) {
          return Right.of(fn(this._value));
        }
      }

      let r1 = Right.of(5).map((x) => x + 5);
      let r2 = Left.of(5).map((x) => x + 5);
      console.log(r1); //=======> Right {_value : 10}
      console.log(r2); //=======> Left {_value : 5}

      function parseJSON(str) {
        try {
          return Right.of(JSON.parse(str));
        } catch (e) {
          return Left.of({ error: e.message });
        }
      }
      let r3 = parseJSON("{name:zs}");
      console.log(r3); //Left {_value: error: "Unexpected token n in JSON at position 1"}

      let r4 = parseJSON('{"name":"zs"}').map((x) => x.name.toUpperCase());
      console.log(r4); // right {_value : }
    </script>
  </body>
</html>
